using DapperExtensionsNew.Data.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace DapperExtensionsNew.Queryable
{
	public class Context
	{
		public DbType Analyzer
		{
			get;
			set;
		}

		public Expression ParametersExpression
		{
			get;
			set;
		}

		public Expression OrderExpression
		{
			get;
			set;
		}

		public Expression SqlExpression
		{
			get;
			set;
		}

		public Expression QueryExpression
		{
			get;
			set;
		}

		public Type ModelType
		{
			get;
			set;
		}

		public Type QueryType
		{
			get;
			set;
		}

		public PropertyInfo[] ModelProperties
		{
			get;
			set;
		}

		public PropertyInfo[] QueryProperties
		{
			get;
			set;
		}

		public IList<Expression> Statements
		{
			get;
			set;
		}

		public Context(Expression sqlExpr, Expression parametersExpr, Expression orderExpr, Expression queryExpr, Type modelType, Type queryType)
		{
			SqlExpression = sqlExpr;
			ParametersExpression = parametersExpr;
			OrderExpression = orderExpr;
			QueryExpression = queryExpr;
			ModelType = modelType;
			QueryType = queryType;
			ModelProperties = modelType.GetProperties().Where(IsValidProperty).ToArray();
			QueryProperties = queryType.GetProperties();
			Statements = new List<Expression>();
			Analyzer = TableCache.GetDialect(ModelType);
		}

		private bool IsValidProperty(PropertyInfo property)
		{
			object[] customAttributes = property.GetCustomAttributes(inherit: false);
			for (int i = 0; i < customAttributes.Length; i++)
			{
				if (customAttributes[i] is IgnoreAttribute)
				{
					return false;
				}
			}
			return true;
		}
	}
}
